//
//  NSObject+PDFThumb.m
//  Documents
//
//  Created by Alex Di Mango on 12/08/12.
//  Copyright (c) 2012 Whardoo.com - All rights reserved.
//

#import "NSObject+PDFThumb.h"
@implementation NSObject (PDFThumb)

-(UIImage*)getThumb:(NSString *)url setW:(int)w setH:(int)h
{
NSURL* pdfFileUrl = [NSURL URLWithString:url];
    CFURLRef docURLRef = (CFURLRef)pdfFileUrl; // CFURLRef from NSURL
    
    
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(docURLRef);
CGPDFPageRef page1;

    CGRect rect = CGRectMake(0, 0, w,h); // thumbnail size
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIImage* thumbnailImage;

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    CGContextSetGrayFillColor(context, 1.0, 1.0);
    CGContextFillRect(context, rect);

    
    // Grab the first PDF page
    page1 = CGPDFDocumentGetPage(pdf,1);
    
    
    NSInteger pageRotate = CGPDFPageGetRotationAngle(page1); // Angle
    
    switch (pageRotate) // Page rotation (in degrees)
    {
        default: // Default case
        case 0: case 180: // 0 and 180 degrees
        {
            // get the rectangle of the cropped inside
            CGRect mediaRect = CGPDFPageGetBoxRect(page1, kCGPDFCropBox);
            CGContextScaleCTM(context, rect.size.width / mediaRect.size.width,
                              rect.size.height / mediaRect.size.height);
            CGContextTranslateCTM(context, -mediaRect.origin.x, -mediaRect.origin.y);
            break;
        }
        case 90: case 270: // 90 and 270 degrees
        {
            CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page1, kCGPDFCropBox, rect, 0, true);
            // And apply the transform.
            CGContextConcatCTM(context, pdfTransform);
            break;
        }
    }
    CGContextDrawPDFPage(context, page1);
    // Create the new UIImage from the context
    thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIImage *xx = [[UIImage alloc]initWithCGImage:thumbnailImage.CGImage scale:1.0 orientation:UIImageOrientationUp];
    
    
    
    //Use thumbnailImage (e.g. drawing, saving it to a file, etc)
    
    CGContextRestoreGState(context);

    UIGraphicsEndImageContext();    
    CGPDFDocumentRelease(pdf);
    
    return xx;

}

@end
